<template>
  <div>
    <h2>购物车</h2>
    <!-- 商品列表 -->
    <ul>
      <li v-for="item in myList" :key="item.id">
        <p>商品</p>
        <p>价格：{{ item.pic }} 元</p>
        <p>数量：{{ item.number }}</p>
        <input type="button" value="+" @click="add(item)" />
        <input type="button" value="-" @click="sub(item)" />

        <p>小计：{{ item.pic * item.number }}</p>
      </li>
    </ul>
    <div class="total">总价：{{ total }}元</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      myList: [
        { number: 1, pic: 10, id: 0 },
        { number: 0, pic: 8, id: 1 },
        { number: 0, pic: 6, id: 2 },
      ],
      total: 0, // 总价
    };
  },
  created() {
    this.count();
  },
  methods: {
    // 减
    sub(item) {
      item.number--;
      if (item.number <= 0) {
        item.number = 0;
      }
      this.count();
    },
    // 加
    add(item) {
      item.number++;
      this.count();
    },
    // 总数
    count() {
      var totalPrice = 0; //临时总价
      this.myList.forEach(function (val, index) {
        totalPrice += val.number * val.pic; //累计总价
      });
      this.total = parseFloat(totalPrice);
    },
  },
};
</script>
<style lang="scss" scoped>
ul li {
  display: flex;
  margin: 10px;
}
h2 {
  // text-align: center;
}
.total {
  margin-left: 50px;
}
</style>
